package com.test;

import junit.framework.TestCase;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * Created by Administrator on 2016/3/14.
 */
public class JMSConsumer extends TestCase {

    public void testConsumer() throws NamingException, InterruptedException {
        Context context = new InitialContext();
        QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup("QueueConnectionFactory");
        QueueConnection connection = null;

        try {
            connection = factory.createQueueConnection();
            connection.start();

            Queue queue = (Queue) context.lookup("MyQueue");
            QueueSession session = connection.createQueueSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(queue);

            consumer.setMessageListener(new MessageListener() {
                public void onMessage(Message message) {
                    try {
                        System.out.println(((TextMessage) message).getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });

            Thread.sleep(30 * 1000);
        } catch (JMSException e) {
            e.printStackTrace();
        } finally {
            try {
                assert connection != null;
                connection.close();
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }

    }

}
